<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测人员管理
 */
namespace app\api\service;

use app\common\model\ImageModel;
use app\common\model\OrderModel;
use app\common\model\StationModel;
use app\common\model\ProtectModel;
use app\common\model\TemplateModel;
use app\common\model\UserModel;
use think\Exception;
use think\Db;
class OrderService
{
    protected static $orderModel;
    protected static $stationModel;
    protected static $protectModel;
    protected static $templateModel;
    protected static $userModel;
    protected static $imageModel;
    protected $type;

    /**
     * OrderService constructor.
     * @param OrderModel $orderModel
     * @param StationModel $stationModel
     * @param ProtectModel $protectModel
     * @param TemplateModel $templateModel
     * @param ImageModel $imageModel
     * @param UserModel $userModel
     */
    public function __construct(OrderModel $orderModel,
                                StationModel $stationModel,
                                ProtectModel $protectModel,
                                TemplateModel $templateModel,
                                ImageModel $imageModel,
                                UserModel $userModel)
    {
        self::$orderModel = $orderModel;
        self::$stationModel = $stationModel;
        self::$protectModel = $protectModel;
        self::$userModel = $userModel;
        self::$imageModel = $imageModel;
        $this->type = 3;
    }

    public function order_list($params)
    {
        if(!isset($params['page']) || empty($params['page']))
        {
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit']))
        {
            $params['limit'] = 1;
        }
        $where = ['user_id'=>$params['tokenId']];
        $count = self::$orderModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count];
        }
        if($params['page'] > 0)
        {
            $result = self::$orderModel->where($where)
                ->page($params['page'], $params['limit'])
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$orderModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $data = [];
        if($result)
        {
            $template_ids = array_column($result->toArray(), 'template_id');
            $template_img_datas = $this->get_template_img($template_ids);
            $result->map(function (&$item){
                $item->user;
                $item->station;
                $item->protect;
                $item->template;
                return $item;
            });

            foreach ($result as $k=>$v)
            {
                $data[$k] = array(
                    'work_id'=>$v['id'],
                    'work_state'=>$v['status'],
                    'dispatch_agency'=>$v['user'] ? $v['user']['nickname'] : '',
                    'dispatch_date'=>$v['dispatch_date'] ? date("Y-m-d H:i:s", $v['dispatch_date']) : '',
                    'accept_date'=>$v['accept_date'] ? date("Y-m-d H:i:s", $v['accept_date']) : '',
                    'finish_date'=>$v['finish_date'] ? date("Y-m-d H:i:s", $v['finish_date']) :
                        '',
                    'remark'=>$v['remark'],
                    'station_msg'=>$v['station'] ? array(
                        'station_id'=>$v['station_id'],
                        'station_name'=>$v['station']['station_name'],
                        'detail'=>$v['station']['detail'],
                        'remark'=>$v['station']['remark'],
                    ) : [],
                    'res_msg'=>$v['protect'] ? array(
                        'res_code'=>$v['res_code'],
                        'res_name'=>$v['protect']['res_name'],
                        'res_detail'=>$v['protect']['res_detail'],
                        'remark'=>$v['protect']['remark'],
                        'date'=>$v['protect']['create_time'] ? date('Y-m-d H:i:s',
                            $v['protect']['create_time']) : '',
                    ) : [],
                    'template_msg'=>$v['template'] ? array(
                        'id'=>$v['template']['id'],
                        'name'=>$v['template']['template_name'],
                        'res_code'=>$v['res_code'],
                        'machine_code'=>'',
                        'template_id'=>'',
                        'proto'=>$v['template']['template_proto'],
                        'res_name'=>$v['protect'] ? $v['protect']['res_name'] : '',
                        'machine_name'=>'',
                        'date' => $v['template']['create_time'] ? date('Y-m-d H:i:s', $v['template']['create_time']) : '',
                        'url' => '',
                        'imgs' => isset($template_img_datas[$v['template_id']]) ?
                            $template_img_datas[$v['template_id']] : []
                    ) : [],
                );
            }
        }
        return ['links' => $data, 'count' => $count];
    }

    /**
     * zws
     * 接受工单
     * @param $params
     * @return bool
     */
    public function update_order($params)
    {
        if(empty($params))
        {
            app_fail(9997);
        }
        if(!isset($params['work_id']) || empty($params['work_id']))
        {
            app_fail(6996);
        }
        $order_data = self::$orderModel->where(['id'=>$params['work_id']])->find();
        if(empty($order_data))
        {
            app_fail(6999);
        }
        if($order_data['user_id'] != $params['tokenId'])
        {
            app_fail(9984);
        }
        if($order_data['status'] != 0)
        {
            app_fail(6998);
        }
        try{
            $update_data = ['status'=>1, 'accept_date'=>time()];
            $result = self::$orderModel->where(['id'=>$params['work_id']])->update($update_data);
            return $result ? true : false;
        }catch (Exception $e){
            app_fail(9899, $e->getMessage());//编辑失败
        }
    }
    /**
     * 获取模板图片
     * @param $template_ids
     * @return array
     */

    public function get_template_img($template_ids)
    {
        if(empty($template_ids) || !is_array($template_ids))
        {
            return [];
        }
        $where = [['template_id', 'in', $template_ids]];
        $datas = [];
        $result = self::$imageModel->where($where)->select();
        $path = config('param_config.imagePath');
        $filePath = config('app.app_host').substr($path, 1);
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['template_id']][] = [
                    'path'=>$v['path'],
                    'img_url'=>$v['img_url'] ? $filePath.$v['img_url'] : ''
                ];
            }
        }
        return $datas;
    }

}